package com.hxkcloud.patient.aerotel;

import android.Manifest;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.activitys.ReportListActivity;
import com.hxkcloud.patient.aerotel.adapter.EcgListAdapter;
import com.hxkcloud.patient.aerotel.datepicker.cons.DPMode;
import com.hxkcloud.patient.aerotel.datepicker.views.DatePicker;
import com.hxkcloud.patient.aerotel.domain.health.AerotelECGPdu;
import com.hxkcloud.patient.aerotel.domain.health.ECGManager;
import com.hxkcloud.patient.aerotel.domain.health.HealthDevice;
import com.hxkcloud.patient.aerotel.domain.health.HealthDeviceManager;
import com.hxkcloud.patient.aerotel.service.AerotelECGReceiveService;
import com.hxkcloud.patient.aerotel.util.ClsUtils;
import com.hxkcloud.patient.aerotel.util.DateUtil;
import com.hxkcloud.patient.permissions.PermissionDialogUtil;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.views.LoadingDialog;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import pub.devrel.easypermissions.EasyPermissions;


/**
 * Created by ricefan on 2016/12/19.
 * Changed by songyuequan on 2016/12/26
 */
public class AerotelActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks, View.OnClickListener {
    public final static int WHAT_ECG_REFRESH = 998;
    public static final int WHAT_RECEIVE_PROGRESS_UPDATE = 997;
    private static final int WHAT_ECG_SERVICE = 225;
    private static final String TAG = AerotelActivity.class.getSimpleName();
    private Spinner spinner;
    private ListView lvECGs;
    private ProgressBar pb = null;
    private String date = null;
    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    private TextView tv_right;
    private TextView tv_help;
    private ArrayAdapter<String> spinnerAdapter;
    private ArrayList<String> dnames = new ArrayList<>();
    //配对监听
    private BroadcastReceiver pairReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
                switch (state) {
                    case BluetoothDevice.BOND_NONE:
                        Log.d(TAG, "BOND_NONE 删除配对");
                        break;
                    case BluetoothDevice.BOND_BONDING:
                        Log.d(TAG, "BOND_BONDING 正在配对");
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        Log.d(TAG, "BOND_BONDED 配对成功");
                        checkECGSeivice();
                        initDevices("请选择设备");
                        break;
                }
            }
        }
    };


    private final Timer timer = new Timer();
    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
            Message message = new Message();
            message.what = WHAT_ECG_SERVICE;
            if (handler != null) {
                handler.sendMessage(message);
            }
        }
    };

    //未找到设备
    private BroadcastReceiver noDevices = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("AerotelActivity", "noDevices onReceive" + intent.getAction());
            if (intent.getAction().equals(ClsUtils.NO_DEVICES)) {
                initDevices("未找到设备");
            }
        }
    };





    //刷新列表
    private BroadcastReceiver refreshECGs = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("AerotelActivity", "noDevices onReceive" + intent.getAction());
            if (intent.getAction().equals(ClsUtils.REFRESH_ECGS)) {
                    loadECGs();
            }
        }
    };
    private RelativeLayout mMyReport;


    /**
     * 清除按钮状态
     */
    private void clearState() {
        tv_right.setClickable(true);
        tv_right.setTextColor(getResources().getColor(R.color.white));
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
    }

    private BroadcastReceiver enable = new BroadcastReceiver() {//监听蓝牙打开
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                switch (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)) {
                    case BluetoothAdapter.STATE_ON://打开蓝牙
                        scanOrLoadBoundDevices();
                        break;
                    case BluetoothAdapter.STATE_OFF://蓝牙关闭
                        intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(intent, 1);
                        break;
                }

            }
        }
    };
    private LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aerotel_activity);
        registerReceiver(pairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
        registerReceiver(noDevices, new IntentFilter(ClsUtils.NO_DEVICES));
        registerReceiver(enable, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
        registerReceiver(refreshECGs, new IntentFilter(ClsUtils.REFRESH_ECGS));
        timer.schedule(task, 2000, 5000);
        pb = (ProgressBar) findViewById(R.id.progressBar);
        TextView tv_title = (TextView) findViewById(R.id.title);
        tv_title.setText("心电监测");
        tv_right = (TextView) findViewById(R.id.tv_right_text);
        mMyReport = (RelativeLayout) findViewById(R.id.my_report);
        tv_help = (TextView) findViewById(R.id.tv_help);
        tv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestBlueToothPermission();
            }
        });
        RelativeLayout back = (RelativeLayout) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mMyReport.setOnClickListener(this);
        spinner = (Spinner) findViewById(R.id.spinDevices);
        spinnerAdapter = new ArrayAdapter<>(this, R.layout.spinner_item, R.id.tvSpinnerItem, dnames);
        spinner.setAdapter(spinnerAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                HealthDevice device = HealthDeviceManager.getDevices().get(position);
                Toast.makeText(AerotelActivity.this, device.getName(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        final TextView dtpicker = (TextView) findViewById(R.id.tvDateSelect);
        dtpicker.setClickable(true);
        dtpicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final AlertDialog dialog = new AlertDialog.Builder(AerotelActivity.this).create();
                dialog.show();
                DatePicker picker = new DatePicker(AerotelActivity.this);
                Calendar calendar = Calendar.getInstance();
                int y = calendar.get(Calendar.YEAR);
                int m = calendar.get(Calendar.MONTH);
                picker.setDate(y, m + 1);
                picker.setMode(DPMode.SINGLE);
                picker.setOnDatePickedListener(new DatePicker.OnDatePickedListener() {
                    @Override
                    public void onDatePicked(String date) {
                        try {
                            date = DateUtil.normalize(date, "yyyy-M-d", DateUtil.DATE_FORMAT);
                        } catch (ParseException e) {
                            e.printStackTrace();
                            date = "";
                        }
                        dtpicker.setText(date);
                        Toast.makeText(AerotelActivity.this, date, Toast.LENGTH_SHORT).show();
                        dialog.dismiss();
                        AerotelActivity.this.date = date;
                        AerotelActivity.this.loadECGs();
                    }
                });
                ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                TextView tv = new TextView(picker.getContext());
                tv.setText("清空");
                tv.setGravity(Gravity.CENTER);
                tv.setPadding(0, 40, 0, 40);
                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dtpicker.setText("选择日期");
                        dialog.dismiss();
                        AerotelActivity.this.date = "";
                        AerotelActivity.this.loadECGs();
                    }
                });
                picker.addView(tv, params);
                tv.bringToFront();

                dialog.getWindow().setContentView(picker, params);
                dialog.getWindow().setGravity(Gravity.CENTER);
            }
        });

        lvECGs = (ListView) findViewById(R.id.listView);
        this.loadECGs();
        initDevices("请选择设备");


        ImageButton fab = (ImageButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                initDevices("请选择设备");
                AerotelActivity.this.loadECGs();
            }
        });
        YjhApplication.aerotelActivity = this;
    }


    /**
     * 开启接收心电数据的服务
     */
    private void startECGService() {
        Intent floatw = new Intent(this, AerotelECGReceiveService.class);
        this.startService(floatw);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(pairReceiver);
        unregisterReceiver(noDevices);
        unregisterReceiver(enable);
        unregisterReceiver(refreshECGs);
    }


    public void loadECGs() {
        List<AerotelECGPdu> ecgs = ECGManager.getECGs(this, date);
        EcgListAdapter adapter = new EcgListAdapter(this, ecgs);
        if (lvECGs != null) {
            lvECGs.setAdapter(adapter);
        }
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (perms.contains(Manifest.permission.BLUETOOTH_ADMIN)&&perms.contains(Manifest.permission.ACCESS_COARSE_LOCATION)&&perms.contains(Manifest.permission.BLUETOOTH)) {
            startBlueToothAndScan();
        }else {
            Toast.makeText(AerotelActivity.this,"未获取足够权限",Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

        if (perms.contains(Manifest.permission.ACCESS_COARSE_LOCATION)) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(AerotelActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                PermissionDialogUtil.show(AerotelActivity.this, "打开蓝牙需要赋予定位权限，请到系统\"设置\">\"应用管理\"中的权限管理允许定位权限，否则蓝牙设备将无法正常工作");
            }
        }

        if (perms.contains(Manifest.permission.BLUETOOTH_ADMIN)) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(AerotelActivity.this, Manifest.permission.BLUETOOTH_ADMIN)) {
                PermissionDialogUtil.show(AerotelActivity.this, "打开蓝牙需要赋予蓝牙权限，请到系统\"设置\">\"应用管理\"中的权限管理允许使用蓝牙权限，否则蓝牙设备将无法正常工作");
            }
        }

        if (perms.contains(Manifest.permission.BLUETOOTH)) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(AerotelActivity.this, Manifest.permission.BLUETOOTH)) {
                PermissionDialogUtil.show(AerotelActivity.this, "打开蓝牙需要赋予蓝牙权限，请到系统\"设置\">\"应用管理\"中的权限管理允许使用蓝牙权限，否则蓝牙设备将无法正常工作");
            }
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    private void requestBlueToothPermission() {
        if (EasyPermissions.hasPermissions(AerotelActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN)) {
            Log.i(TAG,"已经有权限了");
            startBlueToothAndScan();
        } else {
            Log.i(TAG,"请求权限");
            EasyPermissions.requestPermissions(this, "请求蓝牙权限",
                    240, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN);
        }
    }

    /**
     * 清除已经连接的设备并且开始扫描
     */
    private void clearDevicesAndScan() {
        HealthDeviceManager.reload();
        List<HealthDevice> devices = HealthDeviceManager.getDevices();
        for (int i = 0; i < devices.size(); i++) {
            try {
                ClsUtils.removeBond(BluetoothDevice.class, devices.get(i).getDevice());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        bluetoothAdapter.startDiscovery();
    }

    /**
     * 检查是否有连接心电设备
     */
    private boolean checkContains() {
        HealthDeviceManager.reload();
        List<HealthDevice> devices = HealthDeviceManager.getDevices();
        return devices != null && devices.size() > 0;
    }

    /**
     * 开启蓝牙  并且扫描
     */
    private void startBlueToothAndScan() {
        tv_right.setTextColor(getResources().getColor(R.color.gray));
        tv_right.setClickable(false);
        if (!bluetoothAdapter.isEnabled()) {
            bluetoothAdapter.enable();//异步的，不会等待结果，直接返回。
        } else {
            scanOrLoadBoundDevices();
        }
    }

    /**
     * 加载已有的设备或者重新开始扫描
     */
    private void scanOrLoadBoundDevices() {
        if (checkContains()) {
            initDevices("请选择设备");
        } else {
            bluetoothAdapter.startDiscovery();
            loadingDialog = new LoadingDialog(AerotelActivity.this, 0);
            loadingDialog.show();
        }
    }

    public void initDevices(String info) {
        clearState();
        //每次加载设备首先通过DeviceName过滤Aerotel设备
        HealthDeviceManager.reload();
        dnames.clear();
        spinnerAdapter.clear();
//        dnames.add(info);
        for (HealthDevice device : HealthDeviceManager.getDevices()) {
            dnames.add(device.getName());
        }
        spinnerAdapter.notifyDataSetChanged();
    }

    /**
     * 检查ECG服务是否开启
     */
    private void checkECGSeivice() {
        boolean running = false;
        ActivityManager manager = (ActivityManager) AerotelActivity.this.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (service.service.getClassName().contains("AerotelECGReceiveService")) {
                running = true;
                break;
            }
        }
        Log.e(TAG, "running = " + running);
        if (!running) {
            HealthDeviceManager.reload();
            if (HealthDeviceManager.getDevices().size() > 0) {
                startECGService();
            }
        }
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MessageCode.NETWORKCODE_CONNECT_ERROR:
                    Toast.makeText(AerotelActivity.this,"网络异常，请检测网络",Toast.LENGTH_SHORT).show();
                    break;
                case WHAT_ECG_SERVICE:
                    checkECGSeivice();
                    break;
                case WHAT_ECG_REFRESH:
                    initDevices("请选择设备");
                    AerotelActivity.this.loadECGs();
                    break;
                case WHAT_RECEIVE_PROGRESS_UPDATE:
                    int p = msg.getData().getInt("progress");
                    if (pb != null) {
                        if (p > 0 && p < 100) {
                            pb.setVisibility(View.VISIBLE);
                            pb.setProgress(p);
                            pb.invalidate();
                        } else {
                            pb.setVisibility(View.GONE);
                        }
                    }
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.my_report:
                startActivity(new Intent(AerotelActivity.this,ReportListActivity.class));
                break;
        }
    }
}
